import { Button, Divider, ConfigProvider, DatePicker, Modal, message, Tabs, Form, Popconfirm } from 'antd'
import zhCN from 'antd/es/locale/zh_CN';
import { PlusOutlined } from '@ant-design/icons'
import React, { useState, useRef, useEffect } from 'react'
import { PageHeaderWrapper } from '@ant-design/pro-layout'
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table'
import { connect, Link } from 'umi'
import {
  getTransferInfoList,
  saveTransfer,
  deleteTransfer,
  updateTransfer,
  auditTransfer,
  confirmEntryInterface
} from '../service'
import CreateForm from '../components/CreateForm'
import moment from 'moment'
import { BPMStatusEnum, transferTypeList } from '@/utils/constant'

const { TabPane } = Tabs;
const FormItem = Form.Item;

const TableList = (props) => {
  const actionRef1 = useRef();
  const actionRef = useRef();
  const [form] = Form.useForm();
  const [done, setDone] = useState(false);
  const [visible, setVisible] = useState(null);
  const [entryDate, setEntryDate] = useState(false);
  const [entryDateVisible, setEntryDateVisible] = useState(false);
  const [current, setCurrent] = useState(undefined);
  const [selectedOids, setSelectOids] = useState([]);
  const [tabKey, setTabKey] = useState('0');

  const delTransfer = (id) =>{
    //删除员工调动
    deleteTransfer(id).then(r => {
      if (r.flag){
        message.success(`删除调动成功。`);
      }else {
        message.error(r.error);
      }
      actionRef1.current.reload();
    })
  };

  const transfer = (data) => {
    //新增或编辑员工调动
    if (data){
      data.transferDate = data.transferDate?moment(data.transferDate):null;
      data.beginTransferDate = data.beginTransferDate?moment(data.beginTransferDate):null;
      data.endTransferDate = data.endTransferDate?moment(data.endTransferDate):null;
    }
    setCurrent(data);
    setVisible(true);
  };

  const showEntryDateForm = (data) =>{
    setCurrent(data);
    setEntryDateVisible(true);
  };

  const cancelEntry = () => {
    setEntryDate(null);
    setEntryDateVisible(false);
  };

  const confirmEntry = async () => {
    const fieldsValue = await form.validateFields();
    //填写入职日期后确认调动入职
    confirmEntryInterface(current.transferId,moment(fieldsValue.entryDate).format('YYYY-MM-DD')).then(r => {
      if (r.flag){
        message.success(`确认入职成功。`);
      }else {
        message.error(r.error);
      }
      setEntryDate(null);
      setEntryDateVisible(false);
      actionRef1.current && actionRef1.current.reload();
    })
  };

  const columns = [
    {
      title: '工号',
      dataIndex: 'userCode',
      hideInSearch: true,
    },
    {
      title: '姓名',
      dataIndex: 'name',
      render: (item, record) => (
        <Link to={`/info/details/${record.oid}`}>{item}</Link>
      ),
    },
    {
      title: '调转类型',
      dataIndex: 'transferType',
      valueEnum: {
        0: { text: transferTypeList[0].label },
        1: { text: transferTypeList[1].label },
        2: { text: transferTypeList[2].label },
        3: { text: transferTypeList[3].label },
        4: { text: transferTypeList[4].label },
      },
    },
    {
      title: '异动前公司',
      dataIndex: 'beforeOrg',
      hideInSearch: true,
    },
    {
      title: '异动前部门',
      dataIndex: 'beforeDepartment',
      hideInSearch: true,
    },
    {
      title: '异动后公司',
      dataIndex: 'afterOrg',
      hideInSearch: true,
    },
    {
      title: '异动后部门',
      dataIndex: 'afterDepartment',
      hideInSearch: true,
    },
    {
      title: '异动前职级',
      dataIndex: 'beforeJobLevel',
      hideInSearch: true,
    },
    {
      title: '异动后职级',
      dataIndex: 'afterJobLevel',
      hideInSearch: true,
    },
    /*{
      title: '异动日期',
      dataIndex: 'transferDate',
      hideInSearch: true,
      render: (text) => {
        return text ? moment(text).format('YYYY-MM-DD') : '';
      },
    },*/
    {
      title: '异动开始日期',
      dataIndex: 'beginTransferDate',
      hideInSearch: true,
      render: (text) => {
        return text ? moment(text).format('YYYY-MM-DD') : '';
      },
    },
    {
      title: '异动结束日期',
      dataIndex: 'endTransferDate',
      hideInSearch: true,
      render: (text) => {
        return text ? moment(text).format('YYYY-MM-DD') : '';
      },
    },
    {
      title: '创建人',
      dataIndex: 'applyUserName',
      hideInSearch: true,
    },
    {
      title: '审批状态',
      dataIndex: 'auditStatus',
      valueEnum: BPMStatusEnum,
      hideInSearch: true
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      hideInTable: tabKey !== '0',
      render: (item, record) => (
        <>
          {(record.auditStatus === 0) && <>
            <a onClick={() => transfer(record)}>修改</a>
            <Divider type="vertical"/>
            <Popconfirm title={`是否确认删除?`} onConfirm={() => delTransfer(record.transferId)} okText="是" cancelText="否">
              <a>删除</a>
            </Popconfirm>
            <Divider type="vertical"/>
            <a onClick={() => sendAudit(record)}>发起调动</a>
          </>}
          {record.auditStatus !== 0 && record.checkUrl ? <><a onClick={() => window.open(record.checkUrl)}>审批详情</a><Divider type="vertical"/></> : ''}
          {(record.auditStatus === 2 && record.dealStatus === 0) && <> <a onClick={() => showEntryDateForm(record)}>确认到岗</a></>}
        </>
      ),
    },
  ];

  const tabChange = (key) =>{
    setTabKey(key);
    if (key==='0'){
      actionRef1.current && actionRef1.current.reload();
    }else {
      actionRef.current && actionRef.current.reload();
    }
  };

  const handleCancel = () => {
    setCurrent(null);
    setVisible(false);
  };

  const sendAudit = (values) => {
    auditTransfer(values.transferId).then(r => {
      if (r.flag){
        message.success(`发起审核成功。`);
        window.open(r.data);
      }else {
        message.error(r.error);
      }
      actionRef1.current.reload();
    })
  };

  const handleSubmit = (values) => {
    setDone(true);
    setCurrent(null);
    setVisible(false);
    let {saveOrAudit, operationType, ...submitData} = values;
    if (saveOrAudit === 'save'){
      if (operationType === 'add'){
        saveTransfer(submitData).then(r => {
          if (r.flag){
            message.success(`保存调动成功。`);
          }else {
            message.error(r.error);
          }
          actionRef1.current.reload();
        });
      }else {
        updateTransfer(submitData).then(r => {
          if (r.flag){
            message.success(`修改成功。`);
          }else {
            message.error(r.error);
          }
          actionRef1.current.reload();
        });
      }
    }
  };

  return (
    <PageHeaderWrapper>
      <Tabs animated={false} defaultActiveKey={tabKey} onChange={(key) => tabChange(key)}>
        <TabPane tab="未办理" key="0">
          <ProTable
            actionRef={actionRef1}
            rowKey="transferId"
            toolBarRender={(action, { selectedRows }) => [
              <Button type="primary" onClick={() => transfer(null)}>新建</Button>,
            ]}
            request={(params) => getTransferInfoList(params,2,0)}
            columns={columns}
          />
        </TabPane>
        <TabPane tab="已办理" key="1">
          <ProTable
            actionRef={actionRef}
            rowKey="transferId"
            request={(params) => getTransferInfoList(params,2,1)}
            columns={columns}
          />
        </TabPane>
      </Tabs>
      <CreateForm
        done={done}
        current={current}
        visible={visible}
        pageType={2}
        onCancel={handleCancel}
        onSubmit={handleSubmit}
      />
      <ConfigProvider locale={zhCN}>
        <Modal
          title="到岗日期填写"
          visible={entryDateVisible}
          style={{ top: '35%' }}
          onOk={() => confirmEntry()}
          onCancel={() => cancelEntry()}
        >
          <Form
            labelCol={{span: 7}}
            form={form}
          >
            <FormItem name="entryDate" label="到岗日期" rules={[{required: true, message: '到岗日期不能为空！'}]}>
              <DatePicker />
            </FormItem>
          </Form>
        </Modal>
      </ConfigProvider>
    </PageHeaderWrapper>
  )
};

export default connect(({  }) => ({
}))(TableList)
